package com.cqut.forum.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cqut.forum.entity.Role;
import com.cqut.forum.entity.User;
import com.cqut.forum.util.AllowUrl;

public class ForumLevelFilter implements Filter{
	public void destroy() {
		System.out.println("===============自定义过滤器销毁===============");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		String url = req.getRequestURL().toString();
		int index = url.indexOf("/networkforum");
		if(index<0){
			chain.doFilter(request, response);
			return;
		}
		int end = url.lastIndexOf(".");
		
		String action ;
		try{
			if(index<end){
				action = url.substring(index, end);
			}
			else{
				action = "";
			}
		}	
		catch(Exception e){
			resp.sendRedirect("/networkforum/pages/login.html");
			return;
		}
		//管理员操作的界面
		if(AllowUrl.controller.contains(action)){
			User user = (User)req.getSession().getAttribute("user");
			if(user==null){
				resp.sendRedirect("/networkforum/forumcontrol/control_login.html");
				return;
			}
			Role role = user.getRole();
			if(!"管理员".equals(role.getRoleName())&&!"站长".equals(role.getRoleName())){
				resp.sendRedirect("/networkforum/forumcontrol/control_login.html");
				return;
			}
		}
		//需用户登录操作的界面
		if(!AllowUrl.allow.contains(action)){
			User user = (User)req.getSession().getAttribute("user");
			if(user == null){
				resp.sendRedirect("/networkforum/pages/login.html");
				return;
			}
		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("===============进入自定义过滤器===============");
		//System.out.println("===============查询样式放入Application中===============");
		
		//ServletContext application = filterConfig.getServletContext();
		
		
	}

}
